<?php
namespace App\Services;
use Illuminate\Support\Facades\Redis;
use GuzzleHttp\Client;
use App\Services\WorkcustomService;
use App\Services\WorkdataService;
use App\Services\WorkerrorService;
use App\Models\Workcorp;
use App\Models\Worklicense;
use App\Models\Workcorpscontact;
use Config,Log;

class WorkhanddleService
{
    // 取消企业微信授权
    public static function cancelAuth($message)
    {
        Workcorp::workCorpCancel($message['AuthCorpId'],$message['SuiteId']);
        Redis::del("crop_access_token_".$message['AuthCorpId']);
    }

    // 新增企业微信授权
    public static function createAuth($message)
    {
        // 获取永久授权信息
        $bussinessInfo = WorkcustomService::getPermanentCode($message["AuthCode"],$message['SuiteId']);
        Log::info(json_encode($bussinessInfo));
        if (isset($bussinessInfo["errcode"]) && $bussinessInfo["errcode"] != 0) {
            $errmsg = WorkerrorService::getErrorMsg($bussinessInfo["errcode"]);
            return ["status"=>"error","msg"=>$errmsg];
        }
        // 保存更新微信企业数据
        WorkdataService::workCorpInfo($bussinessInfo,"",$message['SuiteId']);
        return ["status"=>"success","msg"=>""];
    }

    // 授权变更通知
    public static function changeAuth($message)
    {
        Log::info("changeAuth-------");
        Log::info($message);
        Log::info("changeAuth-------");
    }

    public static function licensePaySuccess($message)
    {
        $license_order_id = $message["OrderId"];
        $buyer_userid = $message["BuyerUserId"];
        $created_at = $message["TimeStamp"];
        $corp_id = $message["AuthCorpId"];
        // 这里获取的是企业ID，不是应用ID
        $service_corp_id = $message["ServiceCorpId"];
        $config = Config::get("weixin.work.".$service_corp_id);
        $suite_id = $config["suite_id"];
        $workLicense = Worklicense::getLicenseByOrderId($license_order_id);
        $orderAccount = WorklicenseService::licenseListOrderAccount($suite_id,$license_order_id);
        $accountLists = $orderAccount["account_list"];
        if (empty($workLicense)) {
            // 企业微信直接下单的获取多个互通账号
            $orderLists = [];
            $start_time = time();
            $end_time = strtotime("+1 year");
            // 存在BUG后续修复
            foreach ($accountLists as $accountList) {
                $active_code = $accountList["active_code"];
                $orderLists[] = ["corp_id"=>$corp_id,"order_id"=>$license_order_id,"active_code"=>$active_code,"created_at"=>$created_at];
            }
            Worklicense::batchCreaterLicense($orderLists);
        } else {
            // 后台自动单个下单,目前只有1个
            foreach ($accountLists as $accountList) {
                $active_code = $accountList["active_code"];
                // 更新一下激活码
                Worklicense::updateLicenseActiveCodeByOrderId($license_order_id,$active_code);
                // 申请激活互通账号
                $result = WorklicenseService::licenseActiveAccount($suite_id,$active_code,$corp_id,$workLicense->userid);
                if ($result["errcode"] == 0) {
                    // 获取员工
                    $workContact = Workcorpscontact::getWorkCorpsContact($corp_id,$workLicense->userid);
                    $active_time = $workContact->active_time > 1 ? $workContact->active_time : time();
                    if ($workContact->expire_time > 1) {
                        $expire_time = strtotime("+ ".$workLicense->month." months",$workContact->expire_time);
                    } else {
                        $expire_time = strtotime("+ ".$workLicense->month." months");
                    }
                    Workcorpscontact::updateContactActiveTime($workLicense->userid,$active_time,$expire_time);
                }
            }
        }
        return ["status"=>"success","msg"=>""];
    }

    public static function licenseAutoActivate($message)
    {
        $active_code = $message["AccountList"]["ActiveCode"];
        $active_time = $message["TimeStamp"];
        $expire_time = $message["AccountList"]["ExpireTime"];
        $userid = $message["AccountList"]["UserId"];
        $corp_id = $message["AuthCorpId"];
        // 这里获取的是企业ID，不是应用ID
        $service_corp_id = $message["ServiceCorpId"];
        $config = Config::get("weixin.work.".$service_corp_id);
        $suite_id = $config["suite_id"];
        Worklicense::updateLicenseByActiveCode($active_code,$userid,$active_time,$expire_time);
        Workcorpscontact::updateContactActiveTime($userid,$active_time,$expire_time);
        return ["status"=>"success","msg"=>""];
    }

    public static function payForAppSuccess($message)
    {
        $suite_id = $message["SuiteId"];
        $corp_id = $message["PaidCorpId"];
        $created_at = $message["TimeStamp"];
        $userid = $message["OrderId"];
        
        Workorder::createrWorkOrder($corp_id,$suite_id,$order_id,$user_count,$price,$order_period,$created_at);
        return ["status"=>"success","msg"=>""];
    }
}
